package com.example.blades.mygridview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class GridViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_view);

        setTitle("网格视图");
        GridView gv=(GridView) findViewById(R.id.grid_view);
        gv.setAdapter(new ImageAdapter(this));
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context mContext;

        public ImageAdapter(Context c)
        {
            mContext=c;
        }
        //图片的引用定义整型数组 即图片源
        private Integer[] mThumbIds={R.drawable.shell3,
                R.drawable.shell3,R.drawable.shell3,
                R.drawable.shell3,R.drawable.shell3};

        public int getCount()
        {
            return mThumbIds.length;
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageview;
            if(convertView == null)
            {//if it's not recycled,initialize some attributes
                imageview = new ImageView(mContext);
                imageview.setLayoutParams(new GridView.LayoutParams(85,85));
                imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageview.setPadding(8,8,8,8);
            }
            else
            {
                imageview=(ImageView) convertView;
            }

            imageview.setImageResource(mThumbIds[position]);
            return imageview;
        }
    }


}
